package com.cskaoyan.servlet;

import com.cskaoyan.bean.MarketKeyword;
import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.service.AdminKeywordService;
import com.cskaoyan.service.AdminKeywordServiceImpl;
import com.cskaoyan.util.JacksonUtil;
import com.cskaoyan.util.ResponseUtil;
import lombok.SneakyThrows;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author bianyonglei
 * @since 2023/05/31 09:22
 */
@WebServlet("/admin/keyword/*")
public class AdminKeywordServlet extends WdBaseServlet{
    private AdminKeywordService adminKeywordService = new AdminKeywordServiceImpl();
    @SneakyThrows
    private void list(HttpServletRequest request, HttpServletResponse response){
        String keyword = request.getParameter("keyword");
        String url = request.getParameter("url");
        int page = Integer.parseInt(request.getParameter("page"));
        Integer limit = Integer.parseInt(request.getParameter("limit"));
        String sort = request.getParameter("sort");
        String order = request.getParameter("order");
        List<MarketKeyword> marketKeywords = adminKeywordService.list(keyword,url,page,limit,sort,order);
        ResponseUtil.responseOkJsonVo(response, CommonData.data(marketKeywords));
    }

    @SneakyThrows
    private void create(HttpServletRequest request, HttpServletResponse response){
        String requestBody = request.getReader().readLine();
        MarketKeyword marketKeyword = JacksonUtil.read(requestBody, MarketKeyword.class);

        int code = adminKeywordService.create(marketKeyword);
        if(code > 0 ){
            ResponseUtil.responseOkJsonVo(response, marketKeyword);//BaseRespVo.ok(marketKeyword) -> JsonStr -> response.getWriter().println(JsonStr)
        }else {
            ResponseUtil.responseJson(response, BaseRespVo.fail("创建常见问题失败"));
        }
    }



   @SneakyThrows
    private  BaseRespVo update(HttpServletRequest request, HttpServletResponse response){
        String requestBody = request.getReader().readLine();
        MarketKeyword marketKeyword = JacksonUtil.read(requestBody, MarketKeyword.class);
        int row = adminKeywordService.update(marketKeyword);
        if(row == 200){
            //ResponseUtil.responseOkJsonVo(response, marketKeyword);
            return BaseRespVo.ok();
        }
        return BaseRespVo.ok("更新失败！");
    }

    @SneakyThrows
    private BaseRespVo delete(HttpServletRequest request, HttpServletResponse response){
        String requestBody = request.getReader().readLine();
        MarketKeyword marketKeyword = JacksonUtil.read(requestBody, MarketKeyword.class);
        int row = adminKeywordService.delete(marketKeyword);

        if(row == 200){
            return BaseRespVo.ok();
        }else{
           return BaseRespVo.fail("删除失败！");
        }

    }
}
